package com.ttmusic.dao;

import java.util.List;

import com.ttmusic.entity.AlbumInfo;
import com.ttmusic.utils.MusicUtils;
import com.ttmusic.utils.SQLite.SQLiteUtil;

import android.database.Cursor;

/**
 * 专辑信息dao
 * @author Administrator
 *
 */
public class AlbumInfoDao implements BaseDao<AlbumInfo>{
	
	//单例模式
	private AlbumInfoDao() {}
	private static AlbumInfoDao albumDao = new AlbumInfoDao();
	public static AlbumInfoDao getInstance() {
		return albumDao;
	}

	/**
	 * 查找所有专辑信息
	 */
	@Override
	public List<AlbumInfo> findAll() {
		String sql = "select ALBUM_ID,TITLE,ARTIST,NUM_SONGS,ALBUM_ART from TB_ALBUM_INFO ORDER BY ALBUM_ID";
		Cursor cursor = SQLiteUtil.executeQuery(sql);
		return MusicUtils.getAlbumList(cursor);
	}

	/**
	 * 通过主键id查找一个专辑信息
	 */
	@Override
	public AlbumInfo loadById(Long id) {
		String sql = "select ALBUM_ID,TITLE,ARTIST,NUM_SONGS,ALBUM_ART from TB_ALBUM_INFO where ALBUM_ID=?";
		Cursor cursor = SQLiteUtil.executeQuery(sql, id.toString());
		List<AlbumInfo> list = MusicUtils.getAlbumList(cursor);
		if(null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 通过主键id查找一个专辑信息
	 */
	@Override
	public AlbumInfo loadByName(String name) {
		String sql = "select ALBUM_ID,TITLE,ARTIST,NUM_SONGS,ALBUM_ART from TB_ALBUM_INFO where TITLE=?";
		Cursor cursor = SQLiteUtil.executeQuery(sql, name);
		List<AlbumInfo> list = MusicUtils.getAlbumList(cursor);
		if(null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * 保存专辑信息到自己创建的TB_ALBUM_INFO表中
	 * @param artist
	 */
	@Override
	public long save(AlbumInfo album) {
		//插入数据时不填主键  自动递增
		String sql = "insert into TB_ALBUM_INFO(TITLE,ARTIST,NUM_SONGS,ALBUM_ART) values(?,?,?,?)";
		SQLiteUtil.executeDML(sql, album.getTitle(), album.getArtist(), album.getNumSongs(), album.getAlbumArt());
	
		//查找当前插入的数据主键值
		sql = "select MAX(ALBUM_ID) as MAX_ALBUM_ID from TB_ALBUM_INFO";
		Cursor c = SQLiteUtil.executeQuery(sql);
		if(c.getCount() > 0 && c.getColumnCount() > 0) {
			c.moveToNext();
			return c.getLong(c.getColumnIndex("MAX_ALBUM_ID"));
		}
		return -1;
	}

	/**
	 * 修改专辑信息
	 */
	@Override
	public void update(AlbumInfo album) {
		String sql = "update TB_ALBUM_INFO set TITLE=?,ARTIST=?,NUM_SONGS=?,ALBUM_ART=? where ALBUM_ID=?";
		SQLiteUtil.executeDML(sql, album.getTitle(), album.getArtist(), album.getNumSongs(), album.getAlbumArt(), album.getAlbumId());
	}
	
//	/**
//	 * 更新或新增专辑信息
//	 * @param artist
//	 */
//	public void saveOrUpdate(AlbumInfo album) {
//		AlbumInfo alb = this.loadById(album.getAlbumId());
//		if(alb == null) {
//			//专辑不存在 就新增
//			this.save(album);
//		}else {
//			//专辑存在 就修改
//			this.update(album);
//		}
//	}

	/**
	 * 删除专辑信息
	 */
	@Override
	public void delete(Long id) {
		String sql = "delete from TB_ALBUM_INFO where ALBUM_ID=?";
		SQLiteUtil.executeDML(sql, id);
	}

}
